package net.heartbeat.handler.receivers;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import net.heartbeat.handler.HeartbeatMessage;
import net.heartbeat.handler.HeartbeatReceiver;
import net.heartbeat.heartbeats.fixed.FixedHeartbeat;
import net.heartbeat.heartbeats.fixed.FixedHeartbeatTransferer;

/**
 * 测试类：周期性地产生模拟的心跳包，且其来源及内容固定
 * 
 * @author Bai Yu
 *
 */
public class FixedReceiver implements HeartbeatReceiver {
	/**
	 * 接收器，收到的心跳包的来源和内容固定，均为预设值
	 * 
	 * @param source
	 *            固定的来源
	 * @param content
	 *            固定的内容
	 * @param delay
	 *            接收数据的延迟（单位：毫秒）<br>
	 *            每隔这么长时间才收到一个包
	 */
	public FixedReceiver(String source, String content, long delay) {
		this.source = source;
		this. content =  content;
		this.delay = delay;
	}

	@Override
	public HeartbeatMessage accept() throws IOException {
		try {
			Thread.sleep(delay);
		} catch (InterruptedException e) {
		}
		ByteArrayOutputStream rawData = new ByteArrayOutputStream();
		new FixedHeartbeatTransferer().send(new FixedHeartbeat(content), rawData);
		
		return new HeartbeatMessage(source, new ByteArrayInputStream(rawData.toByteArray()));
	}

	private String source;
	private String content;
	private long delay;
}
